package com.blog.config;

import com.google.common.base.Predicates;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/**
 * @Author zqc
 * @Date 2020/11/28-21:10
 * @Description Swagger2配置类
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    /**
     * yml配置文件添加
     * #是否激活 swagger 默认true
     * swagger:
     *   enabled: false
     */
    @Value("${swagger.enabled}")
    private boolean enableSwagger;

    /**
     * @return 创建Docket的Bean对象
     */
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(enableSwagger)      //设置swagger是否启用
                .select()   // 选择那些路径和api会生成document
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))    //对带有RestController注解的api进行监控
//                .apis(RequestHandlerSelectors.any())    // 对所有api进行监控
//                .apis(RequestHandlerSelectors.basePackage("com.blog.controller"))   //对指定包下的api进行监控
                //不显示错误的接口地址
                .paths(Predicates.not(PathSelectors.regex("/error.*"))) //错误路径不监控
                .paths(PathSelectors.regex("/.*"))  // 对根下所有路径进行监控
                .build();
    }

    /**
     * @return 创建ApiInfo的基本信息
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("利用swagger2构建的API文档")
                .description("用restful风格写接口")
                .termsOfServiceUrl("http://localhost:8080/swagger-ui.html")
                .version("2.0")
                .build();
    }

}
